package com.wulian.common.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ResponseHeaderOverrides;
import com.wulian.common.config.OssProperteis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 
* @ClassName: AliyunOSSUtil 
* @Description: TODO(OSS工具类) 
* @author 马志豪
* @date 2019年10月17日 下午3:04:26 
*
 */
@Component
public class AliyunOSSUtil {

    @Autowired(required=false)
   private OssProperteis ossConfig;
    @Autowired(required=false)
    private OSSClient ossClient;

    String internalEndpoint = "oss-cn-beijing-internal.aliyuncs.com";

	private static Logger log = LoggerFactory.getLogger(AliyunOSSUtil.class);
    /**
     * 上传文件到阿里云OSS 并返回文件OSS网络地址
     * @param file
     * @param fileName
     * @return
     * @throws ClientException
     * @throws OSSException
     */
    public  String aliyunOSSFileUpload(InputStream file, String fileName)throws ClientException,OSSException {
        String fileDir = ossConfig.getInternetFileUrl();
        String fallFileName = fileDir+fileName;
        String fileOSSUrl;
        try {
            uploadFile(file, fallFileName);

            URL url = getOSSFileUrl( fallFileName);
            fileOSSUrl = url.toString();
            log.info("url = [" + url + "]");

        } catch (OSSException oe) {
            StringBuilder sb = new StringBuilder();
            sb.append("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            sb.append("Error Message: ");
            sb.append(oe.getErrorCode());
            sb.append("Error Code:       ");
            sb.append(oe.getErrorCode());
            sb.append("Request ID:      ");
            sb.append(oe.getRequestId());
            sb.append("Host ID:           ");
            sb.append(oe.getHostId());
            log.error(sb.toString());
            throw oe;
        } catch (ClientException ce) {
            StringBuilder sb = new StringBuilder();
            sb.append("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            sb.append("Error Message: ");
            sb.append(ce.getMessage());
            log.error(sb.toString());
            throw ce;
        } finally {
            ossClient.shutdown();
        }
        return fileOSSUrl;
    }

    private  void uploadFile(InputStream file,  String fallFileName) {
        ossClient.putObject(ossConfig.getBucketName(), fallFileName, file);
    }

    public   URL getOSSFileUrl( String fallFileName) {
        return ossClient.generatePresignedUrl(ossConfig.getBucketName(), fallFileName, new Date(ossConfig.getExpiredMinutes()));
    }
    public URL getUrl(String fileName,String originalFilename) throws UnsupportedEncodingException {
        OSSClient ossClient=new OSSClient(ossConfig.getEndpoint(),ossConfig.getAccessKeyId(),ossConfig.getAccessKeySecret());
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ossConfig.getBucketName(), fileName);
        // HttpMethod为PUT。
        generatePresignedUrlRequest.setMethod(HttpMethod.GET);
        ResponseHeaderOverrides responseHeaderOverrides = new ResponseHeaderOverrides();
        responseHeaderOverrides.setContentType("application/octet-stream");
        responseHeaderOverrides.setContentDisposition("filename=" + URLEncoder.encode(originalFilename,"UTF-8"));
        generatePresignedUrlRequest.setResponseHeaders(responseHeaderOverrides);

        // 添加Content-Type。
//        generatePresignedUrlRequest.setContentType("application/octet-stream");
        generatePresignedUrlRequest.setExpiration(expiration);
        return ossClient.generatePresignedUrl(generatePresignedUrlRequest);
    }
    public String getIntranetUrl(String fileName){
        return ossConfig.getBucketName()+"."+internalEndpoint+"/"+fileName;
    }
}
